//
//  QMQCIllnessDetailController.m
//  QcMedical1
//
//  Created by 仲启明 on 2016/12/22.
//  Copyright © 2016年 jiawen Du. All rights reserved.
//

#import "QMQCIllnessDetailController.h"
#import "NetWorkTool.h"
#import "QMQCIllDetailModel.h"
#import "NSString+pinyin.h"
@interface QMQCIllnessDetailController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *illDetailArray;
@property (nonatomic, weak) UITextField *search;
@property (nonatomic, strong) NSMutableArray *illUserArray;
@property (nonatomic, assign) BOOL isSearchState;

@end

@implementation QMQCIllnessDetailController



- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadData];
    [self setupUI];
}

- (void)loadData
{
    
    
    NSString *urlString = kSearchCI3Url;
    NSDictionary *dic = @{
                               @"page_size":@15,
                               @"page":@1,
                               @"ci1_id":_detailCellID,
                               @"keyword":@""
                               };
    [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:dic successBloock:^(id responseObject) {
        
        NSArray *array = responseObject[@"data"];
        
        NSArray *detailArray = [NSArray array];
        detailArray = [NSArray yy_modelArrayWithClass:[QMQCIllDetailModel class] json:array];
        
        NSMutableArray *nameArr = [NSMutableArray array];
        
        for (int i = 0; i < detailArray.count; i++) {
            
            QMQCIllDetailModel *model = detailArray[i];
            
            NSString *name = model.ci3_name;
            
            [nameArr addObject:name];
        }
        
        NSMutableArray *illDetailArray = [NSMutableArray array];
        
            for (int i = 0; i < nameArr.count; ++i) {
        
                QMQCIllDetailModel *dto = [[QMQCIllDetailModel alloc] init];
        
                //转拼音
                NSString *PinYin =  [nameArr[i] transformToPinyin];
        
                //首字母
                NSString *FirstLetter = [nameArr[i] transformToPinyinFirstLetter];
        
                //        NSLog(@"pinyin = %@ -- %@",PinYin,FirstLetter);
        
                dto.ci3_name = nameArr[i];
                dto.namePinYin = PinYin;
                dto.nameFirstLetter = FirstLetter;
                
                [illDetailArray addObject:dto];
            }
        self.illDetailArray = illDetailArray.copy;
            
            [self.tableView reloadData];
        
        
    } failureBlock:^(NSError *error) {
        
    }];
}
- (void)setupUI
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    
    
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    
    titleLabel.text =  @"疾病细分";
    
    titleLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:18];
    self.navigationItem.titleView = titleLabel;
    UITextField *searchTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
    
    [self.navigationItem setTitleView:searchTF];
    
    self.search = searchTF;
    
    searchTF.placeholder = @"请输入您要搜索的项目";
    
    searchTF.backgroundColor = [UIColor whiteColor];
    
    searchTF.borderStyle = UITextBorderStyleRoundedRect;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    [self.view addSubview:tableView];
    
    self.tableView = tableView;
    
    tableView.delegate = self;
    
    tableView.dataSource = self;
    
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
    

}
/** 监听 */
- (void)textChange:(NSNotification *)note{

    UITextField *textField = (UITextField *)[note object];

    //如果项目大，搜索的地方多，就要使用多线程，然后在刷新tableview的时候，回到主线程
    [self startSearch:textField.text];
}
-(void)startSearch:(NSString *)string{

    if (self.illUserArray.count>0) {

        [self.illUserArray removeAllObjects];
    }

    //开始搜索
    NSString *key = string.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];

     NSLog(@"key = %@",key);

    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {

        [self.illDetailArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            QMQCIllDetailModel *dto = self.illDetailArray[idx];

            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = dto.ci3_name.lowercaseString;
            NSString *namePinyin = dto.namePinYin.lowercaseString;
            NSString *nameFireLetter = dto.nameFirstLetter.lowercaseString;

            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) { ///比牛 -比

                [tempArr addObject:dto];
            }else{

                if ([nameFireLetter containsString:key]) { //bn - b

                    [tempArr addObject:dto];

                }else{  //ershou

                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {

                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:dto];
                        }
                    }
                }
            }
        }];
        
        NSMutableArray *userArray = [NSMutableArray array];

        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            if (![self.illUserArray containsObject:tempArr[idx]]) {

                [userArray addObject:tempArr[idx]];
                NSLog(@"self.searchResultList  = %@",userArray);

            }
        }];
        
        self.illUserArray = userArray;

        NSLog(@"self.searchResultList  = %@",self.illUserArray);
        self.isSearchState = YES;
    }else{

        self.isSearchState = NO;
    }

    [self.tableView reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        UILabel *noResultLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    
        noResultLab.font = [UIFont systemFontOfSize:20];
        noResultLab.textColor = [UIColor lightGrayColor];
        noResultLab.textAlignment = NSTextAlignmentCenter;
        noResultLab.hidden = YES;
        noResultLab.text = @"抱歉！没有搜索到相关数据";
        tableView.backgroundView = noResultLab;
    
    
        if (_isSearchState) {
    
            if (self.illUserArray.count > 0) {
    
                noResultLab.hidden = YES;
    
                return self.illUserArray.count;
    
            }else{
    
                noResultLab.hidden = NO;
    
                return 0;
            }
        }else{
            
            return self.illDetailArray.count;
        }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    cell.accessoryType = UITableViewCellEditingStyleDelete;
    
        QMQCIllDetailModel *dto = nil;
    
        if (_isSearchState) {
    
            dto = self.illUserArray[indexPath.row];
        }else{
    
            dto = self.illDetailArray[indexPath.row];
        }
    
        cell.textLabel.text = dto.ci3_name;
    cell.textLabel.font = [UIFont fontWithName:@"DiwanMishafi" size:18];
    cell.textLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:18];
        return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = self.tableView.visibleCells[indexPath.row];
    if (_detailBlock) {
        
        _detailBlock(cell.textLabel.text);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
